<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>文件管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 表单 -->
    <el-card class="box-card">
      <el-row :gutter="50">
        <el-col :span="9">
          <el-input placeholder="请输入内容">
            <el-button slot="append" icon="el-icon-search"></el-button>
          </el-input>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" @click="addFile"><i class="iconfont icon-daochu-tianchong" style="margin-right: 5px" ></i>上传文件</el-button>
        </el-col>
      </el-row>

        <!-- file表格 -->
      <el-table v-loading="loading" :data="fileList" border stripe  style="width: 100%;" :header-cell-style="{'text-align':'center'}">
        <el-table-column type="index" align="center"></el-table-column>
        <el-table-column prop="fileName" label="文件名" width="270" :show-overflow-tooltip="true">
            <template slot-scope="scope">
                {{scope.row.fileName}}
                <i v-if="scope.row.fileType =='jpg'||scope.row.fileType =='png'||scope.row.fileType =='jpeg'||scope.row.fileType =='gif'||scope.row.fileType =='pdf' "
                style="margin-left:10px;color:#409EFF;cursor: pointer;"
                @click="showImage(scope.row.fileUrl)"
                class="el-icon-view"></i>    
        </template>
        </el-table-column>
        <el-table-column prop="fileUrl"  width="200" :show-overflow-tooltip="true">
          <template slot="header">
            <span>文件地址</span>
            <el-tooltip popper-class="tooltip" placement="top">
            <i style="margin-left:5px" class="el-icon-warning-outline"></i>
            <div slot="content" class="tooltip-content">
              <div>文件地址仅在测试时展示给前端！</div>
            </div>
          </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center"> </el-table-column> 
        <el-table-column prop="fileSize" label="文件大小" width="110" align="center"> </el-table-column>
        <el-table-column prop="downloadNum" label="下载量" width="80" align="center"> </el-table-column>
        <el-table-column prop="fileType" width="110" align="center">
          <template slot="header">
            <span>文件类型</span>
              <el-tooltip popper-class="tooltip" placement="top">
              <i style="margin-left:5px" class="el-icon-info"></i>
              <div slot="content" class="tooltip-content">
                <div> jpg, png, gif, jpeg, pdf 类型文件可</div>
                <div>点击文件名后面小眼睛进行在线查看！</div>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="操作"  align="center">
            <template slot-scope="scope">
                <el-button type="primary" size="small" icon="el-icon-edit" @click="downloadFile(scope.row)">下载</el-button>
                <el-button type="danger" size="small" icon="iconfont icon-shanchu-tianchong"  @click="openDeleteDialog(scope.row.id)">删除</el-button>
            </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
        </el-pagination>
    </el-card>

    <!-- 上传对话框 -->
    <el-dialog
    title="上传文件"
    :visible.sync="dialogVisible"
    width="40%">
    <!-- 内容主体区域 -->
    <el-upload
    class="upload-demo"
    drag
    :limit="1"
    ref="upload"
    :auto-upload="false"
    action="custom"
    :on-change="handleChange"
    :file-list="uploadFileList"
    :http-request="uploadSignFile">
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    <div class="el-upload__tip" style="text-align:center;" slot="tip">只能上传单个文件，且不超过100M</div>
    </el-upload>
    <!-- 底部区域 -->
    <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUpload">上 传</el-button>
    </span>
    </el-dialog>

    <!-- 预览对话框 -->
    <!-- 上传对话框 -->
    <el-dialog
    title="文件预览"
    :visible.sync="previewVisible"
    width="60%">
    <!-- 内容主体区域 -->
      <iframe
        :src="previewUrl"
        frameborder="no"
        border="0"
        marginwidth="0"
        marginheight="0"
        allowtransparency="yes"
        style="overflow: hidden"
        height="600px;"
        width="100%"
      ></iframe>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
        total:0,
        fileList: [], 
        queryInfo: {
          pagenum: 1,
          pagesize: 5,
        },
      loading : true,
      // 对话框状态  
      dialogVisible: false,
      // 预览框状态
      previewVisible: false,
      previewUrl:'',
      uploadFileList:[],
    }
  },
  created() {
    this.getAllFile()
  },
  methods: {
    //  发送请求获取文件信息数据
    async getAllFile() {
        this.loading = true
      const { data: res } = await this.$http.get('/getAllFile', {
        params: this.queryInfo,
      })
      // 登录失败，弹窗提示错误信息
      if (res.code !== 20000) {
        return this.$message.error(res.message)
      }
      this.fileList = res.data.files.list
      this.total = res.data.files.total
      this.loading = false
    },
    // 下载文件服务
    downloadFile(fileInfo){
    // 第一种方法：window.location = "http://localhost:8090/api/download?id=" + fileInfo.id;
    // 第二种 a标签 注意： 请求头必须要加 responseType: "blob"
      this.$http.get('/download',{ params: {id: fileInfo.id},responseType: "blob" }).then((respond) => {
          // 刷新文件表单,更改下载量
          this.getAllFile()
          if (respond.status === 200) {
          let respondData = respond.data;
          var blob = new Blob([respondData], {
              type: "application/octet-stream",
          });
          var link = document.createElement("a");
          link.download = fileInfo.fileName;//下载文件名
          link.href = window.URL.createObjectURL(blob);
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link); //下载完成移除元素
          window.URL.revokeObjectURL(link.href);
        }
      });
    },
    // 确认上传
    submitUpload() {
      this.$refs.upload.submit();
    },
    // 上传文件改动时触发，用于判断文件是否过大、和 更换文件
    handleChange(file,uploadFileList){
      const isLt100M = file.size / 1024 / 1024 < 100;
      if (!isLt100M) {
        this.$message.error("请上传100M以下的文件!");
        this.$refs.upload.clearFiles();
        return false;
      }
      this.uploadFileList = uploadFileList
    },
    // 单文件上传
    uploadSignFile(param){
      const form = new FormData();
        // file为后端要求上传的参数
        form.append('file', param.file);
        // 发起请求
        this.uploadFileList = []
        this.$http.post('/uploadFile', form,{progress:function(event){
                          param.file.percent = event.loaded/event.total*100
                          param.onProgress(param.file)
                        }}).then((res) => {
          if(res.data.code !== 20000){
            return this.$message.error(res.data.message)
          }
          this.$message.success(res.data.message)
          this.dialogVisible = false
          this.getAllFile()
        })
    },
    // 打开删除确认框
    openDeleteDialog(id){
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '放弃',
          type: 'warning'
        }).then(() => {
          console.log(id)
          this.deleteFile(id)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    // 删除文件
    async deleteFile(id){
      const {data: res} = await this.$http.delete('/deleteFile',{
            //params参数必写 , 如果没有参数传{}也可以
            params: {
              id: id,
            }
        })
        if(res.code !== 20000) return this.$message.error(res.message)
        this.$message.success(res.message)
        this.getAllFile()
    },
    // 打开上传文件对话框
    addFile(){
        this.dialogVisible = true
    },
    // 直接打开浏览图片
    showImage(imageUrl){
      // var tempwindow=window.open('_blank');
      // tempwindow.location = imageUrl;
      this.previewVisible = true
      this.previewUrl = imageUrl
    },
    // 监听 pageSize改变的事件
    handleSizeChange(newPageSize){
        this.queryInfo.pagesize = newPageSize
        this.getAllFile()
    },
    // 页码值改变的事件
    handleCurrentChange(newPage){
        this.queryInfo.pagenum = newPage
        this.getAllFile()
    }
  },
}
</script>

<style lang="less" scoped>
.el-table{
  height: 450px;
  overflow:auto;
}

.el-pagination{
  margin-left: 30px;
  margin-top: 10px;
}
/deep/.el-upload{
    display: flex;
    align-items: center;
    justify-content: center;
}
/deep/.el-popup-parent--hidden {
    padding-right: 0;
}
//下面样式一定需要写在最外层，不能嵌套在el-table或其他样式里面
.tooltip-content {
  div {
    line-height: 18px;
  }
  div:nth-child(3){
    padding:5px 0;
  }
  .indent{
    text-indent: 20px;
  }
}
</style>